package com.pkk.cloud.support.oauth2.config.handle;

import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;

/**
 * @Description: 登出处理的处理
 * @Author: peikunkun
 * @Date: 2020/3/19 0019 下午 2:36
 */
public class Oauth2LogoutHandler implements LogoutHandler {

  private static final Logger logger = LoggerFactory.getLogger(Oauth2LogoutHandler.class);

  @Autowired
  private TokenStore tokenStore;

  /**
   * @Description: 退出操作
   * @Param: request
   * @Param response
   * @Param authentication
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/3/19 0019 下午 2:39
   */
  @Override
  public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Assert.notNull(tokenStore, "tokenStore must be set");
    String token = this.extractToken(request);
    Assert.hasText(token, "token must be set");
    //读取访问令牌信息
    OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
    OAuth2RefreshToken refreshToken;
    if (existingAccessToken != null) {
      if (existingAccessToken.getRefreshToken() != null) {
        logger.info("remove refreshToken!", existingAccessToken.getRefreshToken());
        refreshToken = existingAccessToken.getRefreshToken();
        //删除刷新token的信息
        tokenStore.removeRefreshToken(refreshToken);
      }
      logger.info("remove existingAccessToken!", existingAccessToken);
      //删除访问token信息
      tokenStore.removeAccessToken(existingAccessToken);
    }
  }

  /**
   * @Description: 提取token的信息
   * @Param: request
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2020/3/19 0019 下午 2:36
   */
  private String extractToken(HttpServletRequest request) {
    // first check the header...
    String token = this.extractHeaderToken(request);

    // bearer type allows a request parameter as well
    if (token == null) {
      logger.debug("Token not found in headers. Trying request parameters.");
      token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
      if (token == null) {
        logger.debug("Token not found in request parameters.  Not an OAuth2 request.");
      } else {
        request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE);
      }
    }

    return token;
  }

  /**
   * @Description: 提取token的信息
   * @Param: request
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2020/3/19 0019 下午 2:38
   */
  private String extractHeaderToken(HttpServletRequest request) {
    Enumeration<String> headers = request.getHeaders("Authorization");
    //通常这里只会有一个Authorization
    while (headers.hasMoreElements()) {
      String value = headers.nextElement();
      //获取token的部分
      if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
        String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
        // Add this here for the com.quzeng.oauth2 details later. Would be better to
        // change the signature of this method.
        request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,
            value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim());
        int commaIndex = authHeaderValue.indexOf(',');
        if (commaIndex > 0) {
          authHeaderValue = authHeaderValue.substring(0, commaIndex);
        }
        return authHeaderValue;
      }
    }
    return null;
  }
}
